<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 支付回调通知
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\common\facade\WechatPay;
use app\allwin\model\BankRecharge;
use app\allwin\model\BankBill;
use app\allwin\model\Bank;
use Exception;

class bankNotify extends Base{
    
    /**
     * 充值成功通知
     * @return void
     */
    public function recharge(){
        try{
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function($message,$fail){
                $order = BankRecharge::where(['state'=>0,'order_no' => $message['out_trade_no']])->find();
                if (empty($order)){
                    return true;
                }
                if ($message['return_code'] === 'SUCCESS') {
                    if($message['result_code'] === 'SUCCESS'){
                        $sub_mchid  = $message['sub_mch_id'] ?? '';
                        $ispay = WechatPay::doPay($this->miniapp_id,false,$sub_mchid)->order->queryByOutTradeNumber($order->order_no);
                        if ($ispay['return_code'] === 'SUCCESS') {
                            if ($ispay['result_code'] === 'SUCCESS') {
                                if ($ispay['trade_state'] === 'SUCCESS') {
                                    //充值入账
                                    Bank::recharge($this->miniapp_id, $order->user_id, $order->money);
                                    //充值记录
                                    BankRecharge::where(['id' => $order->id])->update(['state' => 1,'paid_no' => $ispay['transaction_id'],'paid_time'=>strtotime($ispay['time_end'])]);  
                                    //增加日志
                                    BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => 0,'money' => $order->money,'uid'=>$order->user_id,'pay_uid' => $order->user_id], '微信支付[钱包充值]');
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    } 
}